package cn.bonoon.services;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bonoon.core.plugins.ServerService;
import cn.bonoon.entities.ServerEntity;
import cn.bonoon.kernel.support.services.ServiceSupport;

@Service
@Transactional(readOnly = true)
public class ServerServiceImpl extends ServiceSupport implements ServerService {
	/**
	 * 服务器的有效时间，如果多长时间没有更新状态，则表示该服务器已经断开连接 单位为分钟
	 */
	@Value("${server.valid.period}")
	private int validPeriod;

	@Override
	public List<ServerEntity> activities() {
		String ql = "select x from ServerEntity x where x.refreshAt>=? and x.exitAt is null";
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MINUTE, -validPeriod - 5); // -35分钟
		return __list(ServerEntity.class, ql, cal.getTime());
	}

	@Override
	@Transactional
	public void refreshServer(String key, String ips, String osInfo, String jvmInfo, String serverInfo, 
			String cpuInfo, String memoryInfo, String hardDiskInfo, String otherHardwareInfo) {
		String ql = "select x from ServerEntity x where x.key=? order by x.refreshAt desc";
		ServerEntity entity = __first(ServerEntity.class, ql, key);
		Date now = new Date();
		if (null == entity) {
			entity = new ServerEntity();
			entity.setIps(ips);
			entity.setKey(key);
			entity.setStartAt(now);
			entity.setRefreshAt(now);
			entity.setType(TYPE_WEB);
			entity.setOsInfo(osInfo);
			entity.setJvmInfo(jvmInfo);
			entity.setServerInfo(serverInfo);
			entity.setCpuInfo(cpuInfo);
			entity.setMemoryInfo(memoryInfo);
			entity.setHardDiskInfo(hardDiskInfo);
			entity.setOtherHardwareInfo(otherHardwareInfo);
			entityManager.persist(entity);
		} else {
			entity.setIps(ips);
			entity.setRefreshAt(now);
			entityManager.merge(entity);
		}

		ql = "from ServerEntity x where x.key<>? and x.exitAt is null"; // 重启的服务器
		List<ServerEntity> restart_servers = __list(ServerEntity.class, ql, key);
		for (ServerEntity server : restart_servers) {
			server.setExitAt(now);
			entityManager.merge(server);
		}
		
		ql = "from ServerEntity x where x.refreshAt<? and x.exitAt is null"; // 关闭的服务器
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MINUTE, -validPeriod - 5);
		List<ServerEntity> off_servers = __list(ServerEntity.class, ql, cal.getTime());
		for (ServerEntity server : off_servers) {
			server.setExitAt(now);
			entityManager.merge(server);
		}
	}
	
}
